<style lang="less">
    .bookkeeping-list {
        .ivu-table-wrapper {
            border: 0
        }
        .bookkeeping-footer {
            position: absolute;
            bottom: 0;
            right: 0;
            left: 0;
            z-index: 9;
            padding: 16px 8px 20px;
            background: #fff;
            ul {
                display: flex;
                li {
                    margin: 20px 50px 0;
                    align-items: center;

                }
            }
            .bookkeeping-amount {
                font-size: 26px;

                line-height: 40px;
            }
        }
        .ivu-table:after, .ivu-table:before {
            display: none
        }
        .ivu-table th {
            background: #fff;
            border-bottom-width: 2px;
            font-weight: bold
        }
    }
</style>
<template>
    <div class="bookkeeping-list">
        <Row class="pb-10">
            <Button type="primary" @click="showAddFlowModal(1)" v-show="getAccess(accountId,'bookkeeping-add-income-flow')">收入</Button>
            <Button type="primary" @click="showAddFlowModal(-1)" v-show="getAccess(accountId,'bookkeeping-add-expense-flow')">支出</Button>
        </Row>
        <i-table :data="bookData.list" :columns="tableColumns" :height="height"
                 ref="datatable" @on-row-click="showEditFlowModal"></i-table>
        <div class="bookkeeping-footer">
            <ul>
                <li><span class="c-666">筛选后总支出</span>
                    <div class="bookkeeping-amount text-success">-{{bookData.expense | currency}}</div>
                </li>
                <li><span class="c-666">筛选后总收入</span>
                    <div class="bookkeeping-amount text-danger">+{{bookData.income | currency}}</div>
                </li>
                <li><span class="c-666">筛选后结余 </span>
                    <div class="bookkeeping-amount  " :class="bookData.surplus>0?'text-danger':'text-success'">
                        {{bookData.surplus | currency}}
                    </div>
                </li>
                <li><span class="c-666">流水记录数</span>
                    <div class="bookkeeping-amount">{{bookData.recordNumber}}</div>
                </li>
            </ul>
        </div>
        <Modal v-model="editFlowModalVisible" title="修改" @on-ok="editFlow(formItem)">
            <Form :model="formItem" :label-width="80" :rules="ruleValidate">
                <Form-item :label="accountConfig.lenderName" v-show="formItem.lenderAccountId!=accountId" prop="updateLenderAccount">
                    <Select v-model="formItem.lenderAccountId" placeholder="请选择账本名称" >
                        <Option v-for="account in accountList"
                                :value="account.bookkeepingAccountId"
                                v-show="formItem.lenderAccountId!=account.bookkeepingAccountId"
                                :disabled="formItem.lenderAccountId==account.bookkeepingAccountId">
                            {{account.bookkeepingAccountName}}
                        </Option>
                    </Select>
                </Form-item>
                <Form-item :label="accountConfig.debitName" v-show="formItem.debitAccountId!=accountId" prop="updateDebitAccount">
                    <Select v-model="formItem.debitAccountId" placeholder="请选择账本名称">
                        <Option v-for="account in accountList" :value="account.bookkeepingAccountId"
                                v-show="formItem.debitAccountId!=account.bookkeepingAccountId"
                                :disabled="formItem.debitAccountId==account.bookkeepingAccountId">
                            {{account.bookkeepingAccountName}}
                        </Option>
                    </Select>
                </Form-item>
                <Form-item label="金额" v-show="formItem.debitAccountId!=accountId" prop="updateAmount">
                    <Input v-model="formItem.bookkeepingAmount" placeholder="请输入金额,最多两位小数"/>
                    <!--min="0" nullmsg="金额不能为空！" datatype="/^\d+(\.[\d]{1,2})?$/ig"/>-->
                </Form-item>
                <Form-item label="内容" prop="updateContent">
                    <Input v-model="formItem.bookkeepingContent" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                           :number="true" placeholder="请输入流水内容"/>
                </Form-item>
                <Form-item label="日期" prop="updateDate">
                    <Row>
                        <Col>
                        <Date-picker type="date" placeholder="选择日期" v-model="formItem.recordDate"></Date-picker>
                        </Col>
                    </Row>
                </Form-item>
                <Form-item label="模式" prop="updateIsvisible">
                    <Select v-model="formItem.bookkeepingIsvisible" placeholder="请选择模式">
                        <Option value="true">公开</Option>
                        <Option value="false">自己可见</Option>
                    </Select>
                </Form-item>
                <Form-item label="备注" prop="updateNote">
                    <Input v-model="formItem.bookkeepingNote" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                           :number="true" placeholder="请输入流水备注"/>
                </Form-item>

            </Form>

        </Modal>
        <Modal v-model="addFlowModalVisible" title="新增" @on-ok="addFlow(formItem)">
            <Form :model="formItem" :label-width="80" :rules="ruleValidate">
                <Form-item :label="accountConfig.lenderName" v-show="formItem.lenderAccountId!=accountId" prop="addLenderAccount">
                    <Select v-model="formItem.lenderAccountId" placeholder="请选择账本名称">
                        <Option v-for="account in accountList"
                                :value="account.bookkeepingAccountId"
                                v-show="formItem.lenderAccountId!=account.bookkeepingAccountId"
                                :disabled="formItem.lenderAccountId==account.bookkeepingAccountId">
                            {{account.bookkeepingAccountName}}
                        </Option>
                    </Select>
                </Form-item>
                <Form-item :label="accountConfig.debitName" v-show="formItem.debitAccountId!=accountId" prop="addDebitAccount">
                    <Select v-model="formItem.debitAccountId" placeholder="请选择账本名称">
                        <Option v-for="account in accountList" :value="account.bookkeepingAccountId"
                                v-show="formItem.debitAccountId!=account.bookkeepingAccountId"
                                :disabled="formItem.debitAccountId==account.bookkeepingAccountId">
                            {{account.bookkeepingAccountName}}
                        </Option>
                    </Select>
                </Form-item>
                <Form-item label="金额" prop="addAmount">
                    <Input v-model="formItem.bookkeepingAmount" placeholder="请输入金额,最多两位小数"/>
                    <!--min="0" nullmsg="金额不能为空！" datatype="/^\d+(\.[\d]{1,2})?$/ig"/>-->
                </Form-item>
                <Form-item label="内容" prop="addContent">
                    <Input v-model="formItem.bookkeepingContent" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                           :number="true" placeholder="请输入流水内容"/>
                </Form-item>
                <Form-item label="日期" prop="addDate">
                    <Row>
                        <Col>
                        <Date-picker type="date" placeholder="选择日期" v-model="formItem.recordDate"></Date-picker>
                        </Col>
                    </Row>
                </Form-item>
                <Form-item label="模式" prop="addIsvisible">
                    <Select v-model="formItem.bookkeepingIsvisible">
                        <Option value="true">公开</Option>
                        <Option value="false">自己可见</Option>
                    </Select>
                </Form-item>
                <Form-item label="备注" prop="addNote">
                    <Input v-model="formItem.bookkeepingNote" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                           :number="true" placeholder="请输入流水备注"/>
                </Form-item>

            </Form>
        </Modal>
    </div>
</template>
<script>

    import Util from '../../../../libs/util';
    import IOption from "../../../../../node_modules/@tiny/tinyvue/src/components/select/option";
    import ISelect from "../../../../../node_modules/@tiny/tinyvue/src/components/select/select";
    export default {
        components: {
            ISelect,
            IOption
        },
        data () {
            return {
                flowData: {
                    surplus: 0,
                    income: 0,
                    expense: 0,
                    currentUserId: "",
                    lenderName: '',
                    debitName: ''
                },
                addFlowUrl: '',
                editFlowModalVisible: false,
                addFlowModalVisible: false,
                formItem: {},
                accountId: this.$route.params.accountId,
                bookData: {},
                currentFlowList: [],
                isFilter: false,
                filters: {},
                pager: {pageNo: 1, hasPage: true},
                scrollDom: "",
                isLoading: false,
                height: 200,
                creatorList: [],
                typeList: [],
                tableColumns: [
                    {
                        title: '类型',
                        key: 'bookkeepingTypeId',
                        render(row, column){
                            return `{{getBookTypeNameById(row[column.key])}}`;
                        }
                    },
                    {
                        title: '内容',
                        key: 'bookkeepingContent'
                    },
                    {
                        title: '付款方',
                        key: 'lenderAccountId',
                        render(row, column){
                            return `{{getAccountNameById(row[column.key])}}`;
                        }
                    },
                    {
                        title: '收款方',
                        key: 'debitAccountId',
                        render(row, column){
                            return `{{getAccountNameById(row[column.key])}}`;
                        }
                    },
                    {
                        title: '创建者',
                        key: 'createUserName'

                    },
                    {
                        title: '金额',
                        key: 'bookkeepingAmount',
                        className: "text-right",
                        render(row, column){

                            return `<div class="text-right" :class="row.lenderAccountId==accountId?'text-success':'text-danger'">{{row[column.key]|currency}}</div>`;
                        }
                    },
                    {
                        title: '时间',
                        key: 'recordDate'

                    },
                    {
                        title: '操作',
//                        key: 'bookkeepingId',
                        key: 'bookkeepingIsaudit',
                        render (row, column) {

                            return `<Button type="ghost"  @click="changeStatus(row[column.key])"
                                        v-show="getAccess(accountId,'bookkeeping-audit-flow')">审核</Button>&nbsp;
                                    <Button type="ghost"  @click.stop.prevent="deleteFlow(row[column.key])"
                                        v-show="getAccess(accountId,'bookkeeping-delete-flow')||bookkeepingCreatorId== this.$store.state.currentUserId">删除</Button>`;
                        }
                        //fixed: 'right'
                    }
                ],
                formValidate: {
                    addLenderAccount: '',
                    addDebitAccount: '',
                    addAmount: '',
                    addDate: '',
                    addContent: '',
                    addIsvisible: '',
                    updateLenderAccount: '',
                    updateDebitAccount: '',
                    updateAmount: '',
                    updateDate: '',
                    updateContent: '',
                    updateIsvisible: ''
                },
                ruleValidate: {
                    addLenderAccount: [
                        { required: true, message: '付款方不能为空', trigger: 'change' }
                    ],
                    addDebitAccount: [
                        { required: true, message: '收款方不能为空', trigger: 'change' }
                    ],
                    addAmount: [
                        { required: true, message: '金额不能为空', trigger: 'blur' },
                        { type: 'number', min: 0, message: '请输入金额，最多两位小数', trigger: 'blur' }
                    ],
                    addDate: [
                        { required: true, type: 'date',message: '请选择日期', trigger: 'change' }
                    ],
                    addContent: [
                        { required: true, message: '内容不能为空', trigger: 'blur' }
                    ],
                    addIsvisible: [
                        { required: true, message: '请选择模式', trigger: 'change' }
                    ],
                    updateLenderAccount: [
                        { required: true, message: '付款方不能为空', trigger: 'change' }
                    ],
                    updateDebitAccount: [
                        { required: true, message: '收款方不能为空', trigger: 'change' }
                    ],
                    updateAmount: [
                        { required: true, message: '金额不能为空', trigger: 'blur' },
                        { type: 'number', min: 0, message: '请输入金额，最多两位小数', trigger: 'blur' }
                    ],
                    updateDate: [
                        { required: true, type: 'date',message: '请选择日期', trigger: 'change' }
                    ],
                    updateContent: [
                        { required: true, message: '内容不能为空', trigger: 'blur' }
                    ],
                    updateIsvisible: [
                        { required: true, message: '请选择模式', trigger: 'change' }
                    ]
                }
            }

        },
        computed: {
            accountList: function () {
                return this.$store.state.accountList
            },
            accountConfig: function () {
                return this.$store.state.accountConfig
            }
        },
        methods: {
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.$Message.success('提交成功!');
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            },
            getAccess: function (objectId, menuId) {
                let accessMap = this.$store.state.accessList;
                let permissionList = accessMap[objectId];
                if (permissionList) {
                    for (let i = 0, len = permissionList.length; i < len; i++) {
                        if (permissionList[i].permissionType == menuId) {
                            return true;
                        }
                    }
                }
                return false;
            },
            editFlow: function (data) {
                let self = this;
                this.$http.put(self.$store.state.apiHost + "/bookkeeping/api/flow/" + data.bookkeepingId, data).then(function (res) {
                    let currentIndex = null;
                    let flowList = self.bookData.list;
                    for (let i = 0, len = flowList.length; i < len; i++) {
                        if (flowList[i].bookkeepingId == data.bookkeepingId) {
                            currentIndex = i;
                            break;
                        }
                    }
                    flowList.splice(currentIndex, 1, res.data.data);
                })
            },
            changeStatus: function (status) {

            },
            deleteFlow: function (bookkeepingId) {
                let self = this;
                self.$Modal.confirm({
                    title: '警告',
                    content: '一经删除无法恢复,确认删除该流水信息吗？',
                    onOk: () => {
                        self.$http.delete(self.$store.state.apiHost + "/bookkeeping/api/flow/" + bookkeepingId).then(function (res) {
                            let currentIndex = null;
                            let flowList = self.bookData.list;
                            for (let i = 0, len = flowList.length; i < len; i++) {
                                if (flowList[i].bookkeepingId == bookkeepingId) {
                                    currentIndex = i;
                                    break;
                                }
                            }
                            self.bookData.list.splice(currentIndex, 1);
                        })
                    },
                    onCancel: () => {
                    }
                });
            },
            showEditFlowModal: function (rowData) {
                this.editFlowModalVisible = true;
                this.formItem = rowData;
                this.formItem = Object.extend(true, {}, rowData, {bookkeepingIsvisible: String(rowData.bookkeepingIsvisible)});
            },
            showAddFlowModal: function (rowData) {
                this.addFlowModalVisible = true;
                //清空
                this.formItem = null;
                this.formItem = {
                    bookkeepingIsvisible: "true",
//                    recordDate: moment().format("YYYY-MM-DD"),
                    bookkeepingTypeId: this.typeList[0].bookkeepingTypeId,
                    bookkeepingContent: '',
                    bookkeepingNote: ''
                };
//                this.formItem = Object.extend(true, {}, this.formItem, {bookkeepingIsvisible: String(this.formItem.bookkeepingIsvisible)});
                if (rowData == -1) {
                    this.formItem.lenderAccountId = this.accountId;
                    this.formItem.debitAccountId = this.getOtherAccount(this.formItem.lenderAccountId);
                    this.formItem.type = -1;
                    this.addFlowUrl = '/bookkeeping/api/expense/flow';
                } else {
                    this.formItem.debitAccountId = this.accountId;
                    this.formItem.lenderAccountId = this.getOtherAccount(this.formItem.debitAccountId);
                    this.formItem.type = 1;
                    this.addFlowUrl = '/bookkeeping/api/income/flow';
                }
            },
            formatDate (date) {
                return Util.dateFormat(date);
            },
            scrollTable: function () {
                if (this.pager.hasPage && this.tableBodyNode && this.tableBodyNode.scrollTop + this.tableBodyNode.clientHeight - this.tableBodyNode.scrollHeight > -20) {
                    this.showMoreFlow();
                }
            },
            showMoreFlow: function () {
                if (this.isLoading === true) {
                    return false;
                }
                this.getBookKeeping(this.pager.pageNo + 1)
            },
            filterList: function () {

            },
            getBookKeeping: function (page) {
                let self = this;
                if (!page) {
                    page = 1;
                }
                this.isLoading = true;
                this.pager.pageNo = page;
                let requestJson = {
                    accountId: this.accountId,
                    pageNo: page
                };
                if (!requestJson.accountId) return;
                this.$http({
                    url: this.$store.state.apiHost + "/bookkeeping/api/flow",
                    method: "get",
                    params: requestJson
                }).then(function (res) {
                    if (page === 1) {
                        self.bookData = res.data.data;
                    } else {
                        self.bookData.list = self.bookData.list.concat(res.data.data.list);
                    }
                    self.filterList();
                    self.pager.hasPage = res.data.data.list.length !== 0;
                    self.isLoading = false;
                    self.$nextTick(function () {
                        if (res.data.data.list.length !== 0) {
                            self.scrollTable()
                        }
                    })
                })

            },
            initData: function () {
                this.pager.hasPage = true;
                this.pager.pageNo = 1;
                this.isLoading = false;
                this.getBookKeeping(1);
            },
            getOtherAccount: function (accountId) {
                let accountList = this.$store.state.accountList;
                for (let i = 0, len = accountList.length; i < len; i++) {
                    if (accountId != accountList[i].bookkeepingAccountId) {
                        return accountList[i].bookkeepingAccountId;
                        break;
                    }
                }
            },
            getFlowById: function (bookkeepingId) {
                let self = this;
                let flowList = self.bookData.list;
                for (let i = 0, len = flowList.length; i < len; i++) {
                    if (flowList[i].bookkeepingId == bookkeepingId) {
                        return flowList[i];
                        break;
                    }
                }
            },
            getAccountNameById: function (accountId) {

                for (let i = 0, l = this.$store.state.accountList.length; i < l; i++) {
                    if (this.$store.state.accountList[i].bookkeepingAccountId === accountId) {
                        return this.$store.state.accountList[i].bookkeepingAccountName;
                    }
                }
                return "未分类";
            },
            getBookTypeNameById: function (typeId) {
                for (let i = 0, l = this.typeList.length; i < l; i++) {
                    if (this.typeList[i].bookkeepingTypeId === typeId) {
                        return this.typeList[i].bookkeepingTypeTitle;
                    }
                }
                return "未分类";
            },
            setTableHeight: function () {
                const dom = this.$refs["datatable"].$el.parentNode.parentNode;
                this.height = dom.clientHeight - 105;
            },
            addFlow: function (formItem) {
                let self = this;
                this.$http.post(this.$store.state.apiHost + self.addFlowUrl, this.$qs.stringify(formItem)).then(function (res) {
                    self.addFlowModalVisible = false;
                    self.formItem = {};
                    self.bookData.list.push(res.data.data);
                    try {

                    } catch (e) {
                        this.$Message.error('新增流水信息失败');
                    }
                })
            }
        },
        created: function () {
            let self = this;
            this.$http.get(this.$store.state.apiHost + "/bookkeeping/api/flow/data").then(function (res) {
                self.creatorList = res.data.data.creatorList;
                self.typeList = res.data.data.typeList;
                self.$nextTick(function () {
                    self.initData();
                });
            });
            if (self.$store.state.accountList.length == 0) {
                self.$http.get(self.$store.state.apiHost + "/bookkeeping/api/accounts").then(function (res) {
                    self.$store.commit('initAccountList', res.data.data);
                })
            };
            self.$http.get(self.$store.state.apiHost + "/bookkeeping/api/flow/config").then(function (res) {
                self.$store.commit('initAccountConfig', res.data.data);
            });
            self.$http.get(self.$store.state.apiHost + "/bookkeeping/api/access", {
                params: {"objectId": self.accountId}
            }).then(function (res) {
                self.$store.commit('initAccessList', res.data.data);
            });

        }
        ,
        mounted: function () {
            let self = this;
            this.tableBodyNode = this.$refs["datatable"].$refs["tbody"].$el.parentNode;
            this.tableBodyNode.addEventListener('scroll', this.scrollTable);
            window.onresize = function () {
                self.setTableHeight()
            };
            this.setTableHeight();

            let accountList = this.$store.state.accountList;
            let currentIndex = 0;
            for (let i = 0, len = accountList.length; i < len; i++) {
                if (accountList[i].bookkeepingAccountId == this.accountId) {
                    currentIndex = i;
                    break;
                }
            }
            self.currentAccount = accountList[currentIndex];
        }
    }
</script>
